import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, ActionSheetController } from 'ionic-angular';

import { Utils } from '../../providers/providers';
import { Camera } from '@ionic-native/camera';
import { Contact }from '@ionic-native/contacts';

@IonicPage()
@Component({
  selector: 'page-data-maintain',
  templateUrl: 'data-maintain.html',
})
export class DataMaintainPage {
	@ViewChild('fileInput') fileInput;
	private files: any = [];
  private param: any;

  constructor(public navCtrl: NavController, public actionSheetCtrl: ActionSheetController, 
  	public utils: Utils) {
  }

  ngOnInit() {
    this.param = {
      name: '',
      phone: '',
      date: '',
      date2: '',
    }
  }

  selectPic() {
  	if (Camera['installed']()) {
     let actionSheet = this.actionSheetCtrl.create({
     title: '选择照片',
     buttons: [
       {
         text: '相册',
         handler: () => {
           this.getPicture(0);
         }
       },
       {
         text: '相机',
         handler: () => {
           this.getPicture(1);
         }
       },
       {
         text: '取消',
         role: 'cancel',
       }
     ]
   });
   actionSheet.present();
  	}else {
  		 this.fileInput.nativeElement.click();
  	}
  }

  getPicture(type: number) {
    this.utils.getPicture(type).then((imageData) => {
      let base64Image = 'data:image/jpeg;base64,' + imageData;
      this.files.push(base64Image);
      console.log(this.files);
    })
  }

  processWebImage(event) {
    let reader = new FileReader();
    reader.onload = (readerEvent) => {
      let imageData = (readerEvent.target as any).result;
      this.files.push(imageData);
      console.log(this.files);
    };

    reader.readAsDataURL(event.target.files[0]);
  }

  getProfileImageStyle() {
    return 'url(' + this.files[0] + ')'
  }

  getDate() {
    this.utils.getDate(this.param.date2).then((date) => {
      this.param.date2 = date;
    });
  }

  pickContract() {
    this.utils.pickContract().then((item: Contact) => {
      console.log(item);
      this.param.name = item.displayName;
      this.param.phone = item.phoneNumbers[0].value;
    });
  }

  saveContract() {
    this.utils.showLoading();
    setTimeout(() => {
      let name = this.param.name;
      let number = this.param.phone;
      this.utils.saveContract(name, number).then(() => {
        this.utils.hideLoading();
        this.utils.showAlert('保存成功');
      });
    }, 3000);
  }

}
